"use client";

import { createContext, useContext, useEffect, useState, ReactNode } from "react";
import Cookies from "js-cookie";

type Language = "zh" | "en";

interface LanguageContextType {
  language: Language;
  setLanguage: (language: Language) => void;
  isInternational: boolean;
}

const LanguageContext = createContext<LanguageContextType | undefined>(undefined);

const LANGUAGE_COOKIE_KEY = "rosetta_language";

export function LanguageProvider({ children }: { children: ReactNode }) {
  const [language, setLanguageState] = useState<Language>("zh");
  
  // 从cookie读取语言设置
  useEffect(() => {
    const savedLanguage = Cookies.get(LANGUAGE_COOKIE_KEY) as Language;
    if (savedLanguage) {
      setLanguageState(savedLanguage);
    }
  }, []);

  // 设置语言并保存到cookie中
  const setLanguage = (newLanguage: Language) => {
    setLanguageState(newLanguage);
    Cookies.set(LANGUAGE_COOKIE_KEY, newLanguage, { expires: 365 });
  };

  return (
    <LanguageContext.Provider 
      value={{ 
        language, 
        setLanguage,
        isInternational: language === "en"
      }}
    >
      {children}
    </LanguageContext.Provider>
  );
}

export function useLanguage() {
  const context = useContext(LanguageContext);
  if (context === undefined) {
    throw new Error("useLanguage must be used within a LanguageProvider");
  }
  return context;
} 